<?php
/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
defined( '_JEXEC' ) or die( 'Restricted access' );
class FCRegistration {
  public static function register($user_details, $viewer) {
    $db = & JFactory::getDBO();

    $token  = JUtility::getToken();
    JRequest::setVar($token, 1, 'post');
    JRequest::setVar('name', ($viewer->displayName), 'post');
    JRequest::setVar('username', $user_details['username'], 'post');
    JRequest::setVar('email', $user_details['email'], 'post');
    JRequest::setVar('password', $user_details['password'], 'post');
    JRequest::setVar('password2', $user_details['password'],'post');

    define( 'JPATH_COMPONENT',  'components'.DS.'com_user');
    $joomla_reg = new UserController();
    //load language vars that Joomla registration uses (e.g. in emails)
    $lang =& JFactory::getLanguage();
    $lang->load('com_user');
    ob_start();
    $joomla_reg->register_save();
    ob_end_clean();
    //now we must activate this user
    $query = 'SELECT id FROM #__users WHERE username = '.$db->Quote($user_details['username']);
    $db->setQuery($query);
    $user_id = intval($db->loadResult());
    if($user_id) {
      $user =& JUser::getInstance((int)$user_id);
      $user->set('block', '0');
      $user->set('activation', '');
      $user->save();
    }
    $query = 'UPDATE #__users SET email='.$db->Quote($user_details['email']).' WHERE id='.$db->Quote($user_id);
    $db->setQuery($query);
    $db->query();

    return $user_id;
  }
}
